﻿using Microsoft.Extensions.DependencyInjection;
using KeepAccounts.Common.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace KeepAccounts.Api.Extensions
{

    /// <summary>
    /// SqlSugar 启动服务
    /// </summary>
    public static class SqlsugarSetup
    {
        //private static string SqlServerStr = ManagerConfig.GetManagerConfig("ConnectionStrings:SqlServer");

        private static string MySqlStr = ManagerConfig.GetManagerConfig("ConnectionStrings:MySql");



        public static void AddSqlsugarSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));


            //Console.WriteLine($"数据库连接字符串：{SqlServerStr}");

            services.AddScoped<SqlSugar.ISqlSugarClient>(o =>
            {
                var db = new SqlSugar.SqlSugarClient(new SqlSugar.ConnectionConfig()
                {
                    ConnectionString = MySqlStr,//必填, 数据库连接字符串
                    DbType = SqlSugar.DbType.MySql, //(SqlSugar.DbType)BaseDBConfig.DbType,//必填, 数据库类型
                    IsAutoCloseConnection = true,//默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
                                                 //InitKeyType = SqlSugar.InitKeyType.SystemTable//默认SystemTable, 字段信息读取, 如：该属性是不是主键，标识列等等信息


                    InitKeyType = SqlSugar.InitKeyType.Attribute
                });
                //全局过滤器 不查询删除的数据
                db.QueryFilter.Add(new SqlSugar.SqlFilterItem()
                {
                    FilterValue = filterdb =>
                    {
                        return new SqlSugar.SqlFilterResult { Sql = " IsDeleted=0 " };
                    },
                    IsJoinQuery = false
                });

                //db.Aop.OnLogExecuting = (sql, pars) => //SQL执行前事件
                //{
                //    Console.WriteLine("sql:" + sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                //};
                return db;
            });
        }
    }
}
